#!/usr/bin/env jython

# Copyright 2010 Axial Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import cgi         # Eliminate for Python > 2.6 - all references move to the urlparse module
import urllib

import simplejson as json

import org.mule as mule
import org.mule.api

import axialproject.businessobjects.ccrhandler
import axialproject.util.encoders

from urlparse import urlparse
from urllib import unquote_plus
from axialproject.businessobjects.ccrhandler import CCRHandler

reload(axialproject.businessobjects.ccrhandler)
reload(axialproject.util.encoders)


statusCode = { 'OK'                  : 200,
               'BAD_REQUEST'         : 400,
               'NOT_FOUND'           : 404,
               'CONFLICT'            : 409,
               'IM_A_TEAPOT'         : 418,
               'NOT_ACCEPTABLE'      : 406,
               'NOT_IMPLEMENTED'     : 501,
               'SERVICE_UNAVAILABLE' : 503 }


class ClinicalInfoComponent(object):
  # *** Private and protected members ***


  def _processGETAll(self):
    try:
      list = self.handler.fetchAllPatients()

      if len(list) > 0x00:
        self.nStatusHTTP = statusCode['OK']
      else:
        self.nStatusHTTP = statusCode['NOT_FOUND']

      self.response = json.dumps(list, indent = 0x02, default = axialproject.util.encoders.encodePatient)
    except Exception:
      message       = 'Service unavailable; check external connections?'
      self.response = self.setStatusResponse(statusCode['SERVICE_UNAVAILABLE'], message)
      self.log.error(message)

    return self.response


  def _processGETItem(self, elementID = ''):
#     try:
    response = self.handler.fetchPatientByDFN(elementID)

    if response is None:
      response = self.setStatusResponse(statusCode['NOT_FOUND'])
    else:
      self.setStatusResponse(statusCode['OK'])
      response = json.dumps(response, indent = 0x02, default = axialproject.util.encoders.encodePatient)
#     except Exception:
#       message  = 'Service unavailable; check external connections?'
#       response = self.setStatusResponse(statusCode['SERVICE_UNAVAILABLE'], message)
#       self.log.error(message)

    return response
  

  # *** Public methods ***
  def __init__(self, payload, log, eventContext):
    self.contentType  = 'application/json'
    self.contextPath  = None
    self.eventContext = eventContext
    self.log          = log
    self.nStatusHTTP  = statusCode['NOT_FOUND']
    self.payload      = payload
    self.request      = None
    self.response     = None


  def setStatusResponse(self, nStatusHTTP, userMessage = None):
    self.nStatusHTTP = nStatusHTTP
    return json.dumps({ 'nStatus' : nStatusHTTP, 'userMessage' : userMessage }, indent = 0x02)


  def doGET(self):
    t = urlparse(self.request)

    elementID = t[0x02].strip(self.contextPath)

    if len(elementID) > 0x00:
      self.response = self._processGETItem(elementID)
#     elif len(t[0x04]) > 0x00:
#       self.response = self._query(t[0x04])
    else:
      self.response = self._processGETAll()

    return self.response


  def serviceRequest(self):
    if self.eventContext is not None:
      self.contextPath = self.eventContext.message.getProperty('http.context.path')
      self.request     = self.eventContext.message.getProperty('http.request')
      self.payload     = self.eventContext.message.getPayloadAsString()
      method           = self.eventContext.message.getProperty('http.method')

    self.log.info('processing method = '+method)

    self.handler = CCRHandler()

    if method == 'GET':
      self.response = self.doGET()

    responseMessage = mule.DefaultMuleMessage(self.response)
    responseMessage.setProperty('Content-Type', self.contentType)
    responseMessage.setIntProperty('http.status', self.nStatusHTTP)

    return responseMessage

